var OperAct = require('./MajiangOperAct');
var MJModel           = require('./MJModel');
var MJProto           = require('./MJProto');
var RoomProto         = require('../../API/RoomProto');
var HallApi           = require('../../API/HallAPI');
var RoomAPI           = require('../../API/RoomAPI');
var MJLogic           = require('./MJLogic');
var RoomMessageRouter = 'game.gameHandler.roomMessageNotify';
var GameMessageRouter = 'game.gameHandler.gameMessageNotify';

cc.Class({
    extends: cc.Component,

    properties: {
        _dir: 0,
        dir: {
            get() { return this._dir; },
            set(n) {
                this._dir = n;
                this.reset(this._num, null);
            }
        },

        mjprefab: cc.Prefab,
        _mjNodeList: [cc.Node],
        _mjList: [],

        _num: 0,
        num: {
            get() {
                return this._num;
            },
            set(n) {
                this._num = n;
                this.reset(this._num, null);
            },
        },

        _test: 0,
        getMj: {
            get() {
                return this._test;
            },
            set(n) {
                this._test = n;
                if (this._test == -1) {
                    this.clearNewMj();
                } else {
                    this.getNewMj(this._test);
                }
            },
        },

        _outnum: 0,
        outnum: {
            get() { return this._outnum; },
            set(n) {
                this._outnum = n;
                this.testOutList(this._outnum);
            },
        },

        OperAct: OperAct,
		tingNode: cc.Node,
		mjAtlas: cc.SpriteAtlas,

        _outLineNum: 12,
        _newMj: null,
        _outList: [],
        _operList: [],
        _hunpai: 35,
        hunpai: {
            get() { return this._hunpai; },
            set(n) { this._hunpai = n; },
        }
    },

	onLoad: function () {
		Global.MessageCallback.addListener('RoomMessagePush', this);
		Global.MessageCallback.addListener('GameMessagePush', this);
		Global.MessageCallback.addListener('ChooseCardPush', this);
		this._hunpai = 35;
		this._outLineNum = 12;
    },

	setIndex: function (index) {
		this.index = index;
	},

	getChairID: function () {
		if (MJModel.getChairCount() != 2) {
			return (MJModel.getMyChairID()+this._dir)%4;
		}
		else {
			if (this._dir == 1 || this._dir == 3) { /* 左右两个方向不用 */ 
				return 4;
			}
			else if(this._dir == 0) {
				return MJModel.getMyChairID();
			}
			else if(this._dir == 2) {
				return (MJModel.getMyChairID()+1)%2;
			}
		}
	},

	gameInit: function () {
		this.clearAllCards();
		if (MJModel.getGameStatus() == MJProto.gameStatus.NONE) {
		}
		else {
			let cards = MJModel.getHandCardsByChairID(this.getChairID());
			if (!cards) { return; }
			if (cards && cards.length > 0) {
				let operateArray = MJModel.getOperateArrayByChairID(this.getChairID());
				if (MJModel.getCurChairID() == this.getChairID() && operateArray && operateArray.indexOf(MJProto.operateType.QI) != -1) {
					let tingCards = (this._dir==0)? MJLogic.getTingCards(cards, MJModel.getCanHuQidui()):null;
					let card = cards.pop();
					this.reset(cards, tingCards);
					this.getNewMj(card, tingCards);
				}
				else {
					this.reset(cards, null);
				}
			}
			let pengGangArray = MJModel.getPengGangArrayByChairID(this.getChairID());
			for (let i = 0; i < pengGangArray.length; ++i) {
				let item = pengGangArray[i];
				if (item.operate == MJProto.operateType.PENG) {
					this.addOperMj([item.card, item.card, item.card], 'peng', 1, false);
				}
				else {
					this.addOperMj([item.card, item.card, item.card, item.card], (item.operate==MJProto.operateType.GANG_ZHI)? 'angang':'pinggang', 1, false);
				}
			}
			let operateRecord = MJModel.getOperateRecord();
			for (let i = 0; i < operateRecord.length; ++i) {
				let item = operateRecord[i];
				let next = operateRecord[i+1];
				if (next && ([MJProto.operateType.PENG, MJProto.operateType.GANG_CHI, MJProto.operateType.HU_CHI, MJProto.operateType.GANG_BU].indexOf(next.operate) != -1)) {
					continue;
				}
				if (item.chairID == this.getChairID() && item.operate == MJProto.operateType.QI) {
					this.addOutMj(item.card, i==(operateRecord.length-1));
				}
			}
		}
	},

	clearAllCards: function () {
		this.clearMJ();
		this.clearNewMj();
		this.clearOperMjList();
		this.clearOutMjFlag();
		this.clearAllOutMj();
		if (this.tingNode) {
			this.tingNode.active = false;
		}
	},

	messageCallbackHandler: function(router, msg) {
		if(!MJModel.getGameInited()) { return; }
		if (this.getChairID() >= MJModel.getChairCount()) { return; }
		let user = MJModel.getUserByChairID(this.getChairID());
		let sex = 'nv';
		if (user) {
			sex = (user.userInfo.sex == 0)? 'nan':'nv';
		}
		if (router === 'RoomMessagePush') {
			if(msg.type === RoomProto.GET_ROOM_SCENE_INFO_PUSH) {
				this.gameInit();
			}
		}
		else if(router === 'GameMessagePush') {
			if (!MJModel.getUserByChairID(this.getChairID())) { return; }
			if(msg.type === MJProto.GAME_STATUS_PUSH) {
				if (MJModel.getGameStatus() == MJProto.gameStatus.NONE) {
					this.clearAllCards();
				}
				else if (MJModel.getGameStatus() == MJProto.gameStatus.PLAYING) {
					let cards = MJModel.getHandCardsByChairID(this.getChairID());
					this.reset(cards, null); 
				}
			}
			else if(msg.type === MJProto.GAME_SEND_CARDS_PUSH) {
				let cards = MJModel.getHandCardsByChairID(this.getChairID());
				this.reset(cards, null, true); 
				this.playSendCardAnimal(); 
			}
			else if(msg.type === MJProto.GAME_TURN_PUSH) {
				if (msg.data.chairID == this.getChairID() && msg.data.operateArray.indexOf(MJProto.operateType.QI) != -1) {
					let cards = MJModel.getHandCardsByChairID(this.getChairID());
					let tingCards = (this._dir==0)? MJLogic.getTingCards(cards, MJModel.getCanHuQidui()):null;
					if (msg.data.card != null) {
						let newCard = cards.pop();
						this.reset(cards, tingCards); 
						this.getNewMj(newCard, tingCards);
						Global.AudioManager.playSound('Game/Majiang/MJAudio/give');
					}
					else {
						this.reset(cards, tingCards); 
						if (this._dir == 0) {
							for (let node of this._mjNodeList) {
								node.x += 60;
							}
						}
					}
				}
			}
			else if(msg.type === MJProto.GAME_TURN_OPERATE_PUSH) {
				this.unshowCanWinCards();
				let record = MJModel.getOperateRecord();
				if (msg.data.chairID == this.getChairID()) {
					let handCardArr = MJModel.getHandCardsByChairID(msg.data.chairID);
					let mjList = this.getMJList();
					let isSame = true && (handCardArr.length == mjList.length && this._dir == 0);
					if (isSame) {
						handCardArr.sort((a,b)=> a-b);
						mjList.sort((a,b)=> a-b);
						for (let i = 0; i < handCardArr.length; ++i) {
							if (handCardArr[i] != mjList[i]) {
								isSame = false;
								break;
							}
						}
					}
					let lastOperate = record[record.length-1];
					if (!isSame) {
						this.reset(handCardArr, null); 
						let pengGangArray = MJModel.getPengGangArrayByChairID(this.getChairID());
						this.clearOperMjList();
						for (let i = 0; i < pengGangArray.length; ++i) {
							let item = pengGangArray[i];
							if (item.operate == MJProto.operateType.PENG) {
								this.addOperMj([item.card, item.card, item.card], 'peng', 1, i==(pengGangArray.length-1)&&(lastOperate.operate==item.operate));
								if (i==(pengGangArray.length-1) && lastOperate.operate==item.operate) {
									Global.AudioManager.playSound(`Game/Majiang/MJAudio/${sex}/peng`);
								}
							}
							else {
								this.addOperMj([item.card, item.card, item.card, item.card], (item.operate==MJProto.operateType.GANG_ZHI)? 'angang':'pinggang', 1, i==(pengGangArray.length-1)&&(lastOperate.operate==item.operate));
								if (i==(pengGangArray.length-1) && lastOperate.operate==item.operate) {
									Global.AudioManager.playSound(`Game/Majiang/MJAudio/${sex}/gang`);
								}
							}
						}
					}
					if (msg.data.operate == MJProto.operateType.QI && !isSame) {
						if (this.getLastOutMjFlag()) {
							this.clearLastOutMj();
						}
						this.addOutMj(msg.data.card, true);
						Global.AudioManager.playSound(`Game/Majiang/MJAudio/${sex}/`+msg.data.card);
						Global.AudioManager.playSound('Game/Majiang/MJAudio/push');
					}
					else if (msg.data.operate == MJProto.operateType.HU_ZHI && !isSame) {
						this.playOperAct('hu');
						Global.AudioManager.playSound(`Game/Majiang/MJAudio/${sex}/zimo`);
					}
					else if(msg.data.operate == MJProto.operateType.HU_CHI) {
						this.playOperAct('hu');
						Global.AudioManager.playSound(`Game/Majiang/MJAudio/${sex}/hu`);
					}
				}
				else {
					if (msg.data.operate == MJProto.operateType.QI) {
						if (this.getLastOutMjFlag() == true) {
							this.clearOutMjFlag();
						}
					}
					else if (msg.data.operate == MJProto.operateType.PENG || msg.data.operate == MJProto.operateType.HU_CHI || msg.data.operate == MJProto.operateType.GANG_CHI) {
						if (this.getLastOutMjFlag() == true) {
							this.clearLastOutMj();
						}
					}
					else if (msg.data.operate == MJProto.operateType.GUO) {
						if (record.length >= 2) {
							let item = record[record.length-2];
							if (item.operate == MJProto.operateType.QI && item.chairID == this.getChairID()) {
								if (!this.getLastOutMjFlag()) {
									this.addOutMj(item.card, true);
								}
							}
						}
					}
				}
			}
			else if(msg.type === MJProto.GAME_RESULT_PUSH) {
				let cards = MJModel.getHandCardsByChairID(this.getChairID());
				if (cards) {
					this.reset(cards, null); 
					if (this._dir == 0 && msg.data.result.winChairIDArray.indexOf(this.getChairID()) != -1) {
						for (let node of this._mjNodeList) {
							node.x += 60;
						}
					}
				}
			}
		} 
		else if(router === 'ChooseCardPush') {
			if (msg.choosed) {
				for (let node of this._outList) {
					let logic = node.getComponent("MJRes");
					if (logic._mj == msg.choosed) {
						logic.showMask();
					}
					else {
						logic.unshowMask();
					}
				}
				if (this._dir == 0) {
					for (let node of this._mjNodeList) {
						let logic = node.getComponent("MJRes");
						if (logic.onlyid == msg.onlyid) {
							logic.showMask();
						}
						else {
							logic.unshowMask();
						}
					}
				}
			}
			else if(msg.unchoosed) {
				for (let node of this._outList) {
					let logic = node.getComponent("MJRes");
					logic.unshowMask();
				}
				if (this._dir == 0) {
					for (let node of this._mjNodeList) {
						let logic = node.getComponent("MJRes");
						logic.unshowMask();
					}
				}
			}
		}
	},

	getMJList: function () {
		let mjList = [];
		for (let node of this._mjNodeList) {
			mjList.push(node.getComponent('MJRes').majiang);
		}
		return mjList;
	},

	// 本地预操作，不等服务器通知
	localPreOperate: function (operate, card) {
		if (this.getChairID() != MJModel.getMyChairID()) {
			return;
		}
		MJModel.clearOperateArrayByChairID(this.getChairID());
		let user = MJModel.getUserByChairID(this.getChairID());
		let sex = (user.userInfo.sex == 0)? 'nan':'nv';
		let pengGangArray = MJModel.getPengGangArrayByChairID(this.getChairID());
		let handArray = MJModel.getHandCardsByChairID(this.getChairID());
		let record = MJModel.getOperateRecord();

		this.localClearOutMjFlag(operate);
		if (operate == MJProto.operateType.PENG) {
			if (card == null && record.length > 0) {
				card = record[record.length-1].card;
			}
			pengGangArray.push({ operate: operate, card: card, });
			handArray.splice(handArray.indexOf(card), 1);
			handArray.splice(handArray.indexOf(card), 1);
		}
		else if (operate == MJProto.operateType.GANG_ZHI) {
			if (card == null) {
				handArray.sort((a,b) => a-b);
				for (let i = 0; i < handArray.length-3; ++i) {
					if (handArray[i] == handArray[i+1] && handArray[i] == handArray[i+2] && handArray[i] == handArray[i+3]) {
						card = handArray[i];
						pengGangArray.push({ operate: operate, card: card, });
						handArray.splice(handArray.indexOf(card), 1);
						handArray.splice(handArray.indexOf(card), 1);
						handArray.splice(handArray.indexOf(card), 1);
						handArray.splice(handArray.indexOf(card), 1);
						break;
					}
				}
			}
		}
		else if (operate == MJProto.operateType.GANG_BU) {
			if (card == null) {
				card = handArray[handArray.length-1];
			}
			// for (let item of pengGangArray) {
			for (let i = 0; i < pengGangArray.length; ++i) {
				let item = pengGangArray[i];
				if (item.operate == MJProto.operateType.PENG && item.chairID == this.getChairID() && item.card == card) {
					pengGangArray[i] = {
						operate: operate,
						card: item.card,
						chairID: item.chairID,
					};
				}
			}
			handArray.splice(handArray.indexOf(card), 1);
		}
		else if (operate == MJProto.operateType.GANG_CHI) {
			if (card == null && record.length > 0) {
				card = record[record.length-1].card;
			}
			pengGangArray.push({ operate: operate, card: card, });
			handArray.splice(handArray.indexOf(card), 1);
			handArray.splice(handArray.indexOf(card), 1);
			handArray.splice(handArray.indexOf(card), 1);
		}
		else if (operate == MJProto.operateType.QI) {
			handArray.splice(handArray.indexOf(card), 1);
			this.addOutMj(card, true);
			Global.AudioManager.playSound(`Game/Majiang/MJAudio/${sex}/`+card);
			Global.AudioManager.playSound('Game/Majiang/MJAudio/push');
		}
		else if (operate == MJProto.operateType.HU_ZHI) {
			this.playOperAct('hu');
			Global.AudioManager.playSound(`Game/Majiang/MJAudio/${sex}/zimo`);
		}
		else if (operate == MJProto.operateType.GUO) {
		}

		if ([MJProto.operateType.PENG, MJProto.operateType.GANG_ZHI, MJProto.operateType.GANG_CHI, MJProto.operateType.GANG_BU].indexOf(operate) != -1) {
			this.clearOperMjList();
			for (let i = 0; i < pengGangArray.length; ++i) {
				let item = pengGangArray[i];
				if (item.operate == MJProto.operateType.PENG) {
					this.addOperMj([item.card, item.card, item.card], 'peng', 1, i==(pengGangArray.length-1));
					if (i==(pengGangArray.length-1)) {
						Global.AudioManager.playSound(`Game/Majiang/MJAudio/${sex}/peng`);
					}
				}
				else {
					this.addOperMj([item.card, item.card, item.card, item.card], (item.operate==MJProto.operateType.GANG_ZHI)? 'angang':'pinggang', 1, i==(pengGangArray.length-1));
					if (i==(pengGangArray.length-1)) {
						Global.AudioManager.playSound(`Game/Majiang/MJAudio/${sex}/gang`);
					}
				}
			}
		}
		this.reset(handArray, null); 
		if ([MJProto.operateType.PENG, MJProto.operateType.HU_ZHI].indexOf(operate) != -1) {
			if (this._dir == 0) {
				for (let node of this._mjNodeList) {
					node.x += 60;
				}
			}
		}
	},

	playSendCardAnimal: function () {
		let posArray = [];
		let posx = 0, posy = 0;
		for (let cardNode of this._mjNodeList) {
			let pos = cardNode.getPosition();
			posArray.push(pos);
			posx += pos.x;
			posy += pos.y;
		}
		posx /= this._mjNodeList.length;
		posy /= this._mjNodeList.length;
		for (let i = 0; i < posArray.length; ++i) {
			let cardNode = this._mjNodeList[i];
			cardNode.setPosition(cc.v2(posx, posy));
			cardNode.runAction(cc.moveTo(0.5, posArray[i]));
		}
	},

	setDirPos: function () {
		if (this._dir == 0) {
			this._beginX = 472; //手持麻将开始的坐标x
			this._beginY = -290; //手持麻将开始的坐标y
			this._intervalX = -88; //手持麻将坐标x 间隔
			this._intervalY = 0; //手持麻将坐标y 间隔
			this._newX = 592; //摸牌麻将坐标x 
			this._newY = -290; //摸牌麻将坐标y

			this._outBeginX = -235; //出牌麻将开始的坐标x
			this._outBeginY = -100; //出牌麻将开始的坐标y
			this._outIntervalX = 40; //出牌麻将 x轴间隔   兼容操作用牌的横轴间隔
			this._outIntervalY = -46; //出牌麻将 y轴间隔   兼容操作用牌的横轴间隔

			this._operationX = -600; //操作麻将（吃碰杠）开始的坐标x
			this._operationY = -297; //操作麻将（吃碰杠）开始的坐标y
			this._operationIntervalX = 20; //操作麻将（吃碰杠）x轴间隔
			this._operationIntervalY = 22; //操作麻将（吃碰杠）y轴间隔
			this._operationIntervalY2 = 0; //操作麻将（吃碰杠）两堆 y轴间隔
			if (MJModel.getChairCount() == 2) {
				this._outBeginX = -340;
				this._outLineNum = 18;
			}
		} 
		else if (this._dir == 1) {
			this._beginX = 480;
			this._beginY = 200;
			this._intervalX = 0;
			this._intervalY = -26;
			this._newX = 480;
			this._newY = 240;
			this._outBeginX = 300;
			this._outBeginY = -134;
			this._outIntervalX = 49;
			this._outIntervalY = 27;

			this._operationX = 440+40;
			this._operationY = -155-30;
			this._operationIntervalX = 20;
			this._operationIntervalY = 26;
			this._operationIntervalY2 = 11;
		} 
		else if (this._dir == 2) {
			this._beginX = -300;
			this._beginY = 290;
			this._intervalX = 38;
			this._intervalY = 0;
			this._newX = -350;
			this._newY = 290;
			this._outBeginX = 170;
			this._outBeginY = 140;
			this._outIntervalX = -36;
			this._outIntervalY = 42;

			this._operationX = 220;
			this._operationY = 290;
			this._operationIntervalX = -20;
			this._operationIntervalY = 13;
			this._operationIntervalY2 = 0;
			if (MJModel.getChairCount() == 2) {
				this._outBeginX = 300;
				this._outLineNum = 18;
			}
		} 
		else if (this._dir == 3) {
			this._beginX = -500;
			this._beginY = -130;
			this._intervalX = 0;
			this._intervalY = 26;
			this._newX = -500;
			this._newY = -176;
			this._outBeginX = -320;
			this._outBeginY = 160;
			this._outIntervalX = -49;
			this._outIntervalY = -27;

			this._operationX = -495;
			this._operationY = 220+30;
			this._operationIntervalX = -20;
			this._operationIntervalY = -26;
			this._operationIntervalY2 = 11;
		}
	},

	clearMJ() {
		for (let i = this._mjNodeList.length; i > 0; i--) {
			let mj = this._mjNodeList[i - 1];
			mj.destroy();
		}
		this._mjNodeList = [];
	},

	showShaiPai(shaipai) {
		if (shaipai != null && shaipai != 0) {
			this.ShaiPaiNode.active = true;
			let reslogic = this.ShaiPaiNode.getChildByName('MaJiang').getComponent('MJRes');
			reslogic.majiang = shaipai;
		}
	},

	reset: function (list, tingCards, animal) {
		if (this._dir == 0) {
			this.showTing(list.slice());
			Global.MessageCallback.emitMessage('ChooseCardPush', { unchoosed: 1 });
		}
		if (typeof (list) == 'number') {
			let num = list;
			list = [];
			for (let i = 0; i < num; i++) {
				list.push(36);
			}
		}
		this.clearMJ();
		this.setDirPos();

		let hunpailist = [];
		if (this._hunpai != 0) {
			let delhunpai = (plist, k) => {
				for (let i = k; i < plist.length; i++) {
					let p = plist[i];
					if (p == this._hunpai) {
						hunpailist.push(p);
						plist.splice(i, 1);
						return delhunpai(plist, i);
					}
				}
				return plist;
			}
			list = delhunpai(list, 0);
		}
		list.sort((a, b) => { return b - a; });
		if (this._hunpai != 0) {
			for (let i = 0; i < hunpailist.length; i++) {
				list.push(hunpailist[i]);
			}
		}

		let self = this;
		this._mjList = list;
		for (let i = 0; i < list.length; i++) {
			let point = list[i];
			let mj = cc.instantiate(this.mjprefab);
			let reslogic = mj.getComponent('MJRes');
			reslogic.onlyid = i;
			reslogic.dir = this._dir;
			reslogic.isStand = true;
			if (tingCards && tingCards.indexOf(point) != -1) {
				reslogic.tingFlag = true;
			}
			if (this._dir == 0) {
				reslogic.canSend = true;
				reslogic.selectFunc = () => { self.selectAMj(i); };
				mj.setScale((83+5)/83, (125+7.5)/125);
			}
			else if(MJModel.getGameStatus() == MJProto.gameStatus.RESULT) {
				reslogic.isStand = false;
				reslogic.isShow = true;
			}
			if (animal) {
				reslogic.isStand = false;
				reslogic.isShow = false;
				if (this._dir == 0) {
					mj.setScale(85/55*1.1);
				}
			}
			this.setMjPoint(mj, point);

			mj.x = this._beginX + i * this._intervalX;
			mj.y = this._beginY + i * this._intervalY;
			mj.parent = this.node;
			mj.zIndex = (320 - mj.y);
			this._mjNodeList.push(mj);
		}
	},

	showTing: function (list) {
		let canHu = MJLogic.canHu(list, 35, MJModel.getCanHuQidui());
		if (this.tingNode) {
			if (this._dir == 0 && canHu) {
				this.tingNode.active = true;
				this.tingNode.zIndex = 999;
				let Layout = cc.find('Layout', this.tingNode);
				for (let node of Layout.children) {
					node.destroy();
				}
				let item = cc.find('Item', this.tingNode);
				let canWinCards = MJLogic.getCanWinCards(list, MJModel.getCanHuQidui());
				for (let card of canWinCards) {
					let node = cc.instantiate(item);
					node.active = true;
					node.y = 0;
					node.parent = Layout;
					let str = "down_"+Math.floor(card/10)+"_"+(card%10);
					node.getComponent(cc.Sprite).spriteFrame = this.mjAtlas.getSpriteFrame(str);
				}
				let bg = cc.find('bg', this.tingNode);
				this.scheduleOnce(() => {
					bg.width = Layout.width+50;
				}, 0);

			}
			else {
				this.tingNode.active = false;
			}
		}
	},

	setMjPoint(node, n) {
		let reslogic = node.getComponent('MJRes');
		if (n == null) { n = 36; }
		if (this._hunpai == n) {
			reslogic.isHun = true;
		} 
		reslogic.majiang = n;
	},

	setMjs(list) {
		if (this._dir != 0) {
			return;
		}
		for (let index = 0; index < list.length; index++) {
			const point = list[index];
			let mjnode = this._mjNodeList[index];
			this.setMjPoint(mjnode, point);
		}
	},

    clearNewMj() {
        if (this._newMj) {
            let index = this._mjNodeList.indexOf(this._newMj);
            if (index != -1) {
                this._mjNodeList.splice(index, 1);
            }
            this._newMj.destroy();
            this._newMj = null;
        }
    },

	getNewMj: function (n, tingCards) {
        this.clearNewMj();
        this._newMj = cc.instantiate(this.mjprefab);
        let reslogic = this._newMj.getComponent('MJRes');
        reslogic.dir = this._dir;
        reslogic.onlyid = 13;
        reslogic.isStand = true;

        this._newMj.x = this._newX;
        this._newMj.y = this._newY;
        this._newMj.zIndex = (320 - this._newMj.y);
        this._newMj.parent = this.node;

        if (this._dir == 0) {
            reslogic.canSend = true;
			reslogic.tingFlag = (tingCards && tingCards.indexOf(n) != -1);
            let self = this;
            reslogic.selectFunc = () => {
                self.selectAMj(reslogic.onlyid);
            };
            if (n != 0) {
                this.setMjPoint(this._newMj, n);
            }
			this._newMj.setScale((83+5)/83, (125+7.5)/125);
        }
        this._mjNodeList.push(this._newMj);
    },

    clearLastOutMj() {
        this.clearOutMj(this._outList.length - 1);
    },

    clearOutMj(index) {
        if (this._outList[index] == null) {
            return;
        }
        this._outList[index].destroy();
        delete this._outList[index];
        this._outList.splice(index, 1);
    },

	getLastOutMjFlag () {
		let lastNode = null;
		if (this.outList && this.outList.length > 0) {
			lastNode = this._outList[this._outList.length-1]
		}
		if (!lastNode) {
			return null;
		}
		else {
            let reslogic = lastNode.getComponent('MJRes');
			return reslogic.flaglast;
		}
	},

    clearOutMjFlag() {
        for (let i = 0; i < this._outList.length; i++) {
            const mj = this._outList[i];
            let reslogic = mj.getComponent('MJRes');
            if (reslogic.flaglast) {
                reslogic.flaglast = false;
            }
        }
    },

	localClearOutMjFlag (operate) {
		for (let i = 1; i <= 4; ++i) {
			let cardNode = cc.find('Cards'+i, this.node.parent);
			if (cardNode && cardNode.active) {
				let logic = cardNode.getComponent('MJCards');
				if (logic.getLastOutMjFlag()) {
					if (operate == MJProto.operateType.QI) {
						logic.clearOutMjFlag();
					}
					else if([MJProto.operateType.PENG, MJProto.operateType.GANG_CHI].indexOf(operate) != -1) {
						logic.clearLastOutMj();
					}
				}
			}
		}
	},

    addOutMj(n, flag = true) {
        if (n == 0) { return; }
        let outmj = cc.instantiate(this.mjprefab);
        let reslogic = outmj.getComponent('MJRes');
        reslogic.dir = this._dir;
        reslogic.majiang = n;
        reslogic.isStand = false;
        reslogic.isShow = true;
        reslogic.flaglast = flag;

        let i = this._outList.length;
        let l = Math.floor(i / this._outLineNum);
        let x = this._outBeginX + (i % this._outLineNum) * this._outIntervalX;
        let y = this._outBeginY + this._outIntervalY * l;
        /* if (l > 1) {
            x = this._outBeginX + this._outLineNum * this._outIntervalX;
            y = this._outBeginY + this._outIntervalY * (l - 1);
        } */
        if (this._dir == 1 || this._dir == 3) {
            x = this._outBeginX + this._outIntervalX * Math.floor(i / this._outLineNum);
            y = this._outBeginY + (i % this._outLineNum) * this._outIntervalY;
        }
		if (this._dir == 0) {
			outmj.setContentSize(40, 61);
		}
        outmj.x = x;
        outmj.y = y;
        outmj.zIndex = (320 - outmj.y);
        outmj.parent = this.node;
        this._outList.push(outmj);
    },

    clearOperMjList() {
        for (let i = 0; i < this._operList.length; i++) {
            let item = this._operList[i];
            let list = item.nodelist || [];
            for (let n = 0; n < list.length; n++) {
                let node = list[n];
                node.destroy();
            }
        }
        this._operList = [];
    },

    makeMj(n, show = false) {
        let mj = cc.instantiate(this.mjprefab);
        let reslogic = mj.getComponent('MJRes');
        reslogic.dir = this._dir;
        reslogic.majiang = n;
        reslogic.isStand = false;
        reslogic.isShow = show;
        return mj
    },

    addOperMj(mjlist, mjtype = 'pt', operpos = 1, needact = true) {
        let beginx = 0;
        let beginy = 0;
        mjlist.sort();
        let nodelist = [];

        for (let i = 0; i < mjlist.length; i++) {
            let fix_zorder_y = 0;
            let point = mjlist[i];
            let isshow = false;
            if ('peng' == mjtype || ('angang' == mjtype && i == 3) || 'pinggang' == mjtype) {
                isshow = true;
            }
            let mj = this.makeMj(point, isshow);
            let x = 0;
            let y = 0;
            if (this._dir == 0 || this._dir == 2) {
				let _outIntervalX = (this._dir == 0)? 73:this._outIntervalX; /* don't touch */ 
                let beginx = this._operationX + this._operList.length * (_outIntervalX * 3 + this._operationIntervalX);
                x = beginx + i * _outIntervalX;
                y = this._operationY;
                if (('angang' == mjtype || 'pinggang' == mjtype) && i == 3) {
                    x = beginx + operpos * _outIntervalX;
                    y = this._operationY + this._operationIntervalY;
                    fix_zorder_y = 100;
                }
            }
            if (this._dir == 1 || this._dir == 3) {
                x = this._operationX;
                let beginy = this._operList.length * (this._operationIntervalY * 3 + this._operationIntervalX);
                y = this._operationY + beginy + i * this._outIntervalY;
                /* if (mjtype == 'angang') {
                    y = this._operationY + beginy + i % 2 * this._outIntervalY + this._operationIntervalY2 * Math.floor(i / 2);
                    fix_zorder_y = Math.floor(i / 2) > 0 ? 100 : 0;
                } */
                if (('angang' == mjtype || 'pinggang' == mjtype) && i == 3) {
                    let node = nodelist[operpos];
                    y = node.y + this._operationIntervalY2;
                    fix_zorder_y = 100;
                }
            }
            mj.parent = this.node;
            mj.x = x;
            mj.y = y;
            mj.zIndex = (320 - mj.y + fix_zorder_y);
			if (this._dir == 0) {
				mj.setScale(73/53); 
			}
            nodelist.push(mj);
        }
        let operitem = {
            type: mjtype,
            mjlist: mjlist,
            nodelist: nodelist,
        }
        this._operList.push(operitem);
        if (needact) {
            this.playOperAct(mjtype);
        }
    },

    playOperAct(mjtype) {
        if ('chi' == mjtype) {
            this.OperAct.play(0);
        } else if ('peng' == mjtype) {
            this.OperAct.play(1);
        } else if ('angang' == mjtype || 'pinggang' == mjtype || 'wangang' == mjtype) {
            this.OperAct.play(2);
        } else if ('hu' == mjtype) {
            this.OperAct.play(3);
        } else if ('zimo' == mjtype) {
            this.OperAct.play(4);
        }
    },


    clearAllOutMj() {
        for (let i = this._outList.length - 1; i >= 0; i--) {
            this.clearOutMj(i);
        }
    },

    testOutList(n) {
        this.clearAllOutMj();
        this._outList = [];
        for (let i = 0; i < n; i++) {
            this.addOutMj(36);
        }
    },

    outList(list, islastout = false) {
        this.clearAllOutMj();
        let flag = false;
        for (let i = 0; i < list.length; i++) {
            const mj = list[i];
            if (i == list.length - 1 && islastout) {
                flag = true;
            } 
            this.addOutMj(mj, flag);
        }
    },

    selectAMj(onlyid) {
        if (this._dir == 0) {
			Global.AudioManager.playCommonSoundClickButton();
			this.unshowCanWinCards();
			let operateArray = MJModel.getOperateArrayByChairID(this.getChairID());
			let canQi = operateArray && (operateArray.indexOf(MJProto.operateType.QI) != -1);
            for (let i = 0; i < this._mjNodeList.length; i++) {
                let mjnode = this._mjNodeList[i];
                let mjlogic = mjnode.getComponent('MJRes');

                if (mjlogic.onlyid == onlyid) {
                    if (mjlogic._isSelect) {
						if (canQi) {
							if (mjlogic._mj == 35) {
								console.log("重设位置2");
								Global.DialogManager.addPopDialog("确定要打出红中吗？", () => {
									Global.NetworkManager.notify(GameMessageRouter, MJProto.gameOperateNotify(mjlogic._mj, MJProto.operateType.QI));
									this.localPreOperate(MJProto.operateType.QI, mjlogic._mj);
								}, () => {
									mjlogic.resetPos();
								});
							}
							else {
								Global.NetworkManager.notify(GameMessageRouter, MJProto.gameOperateNotify(mjlogic._mj, MJProto.operateType.QI));
								this.localPreOperate(MJProto.operateType.QI, mjlogic._mj);
							}
						}
						else {
							mjnode.y = this._beginY;
							mjlogic._isSelect = false;
						}
						Global.MessageCallback.emitMessage('ChooseCardPush', { unchoosed: mjlogic._mj });
                    } 
					else {
						if (mjlogic.tingFlag) {
							this.showCanWinCards(mjlogic._mj);
						}
						Global.MessageCallback.emitMessage('ChooseCardPush', {
							choosed: mjlogic._mj,
							onlyid: mjlogic.onlyid,
						});
                        mjnode.y = this._beginY+40;
                        mjlogic._isSelect = true;
                    }
                } else {
                    mjnode.y = mjlogic._oldy;
                    mjlogic._isSelect = false;
                }
            }
        }
    },

	showCanWinCards: function (card) {
		let huTipNode = cc.find('HuTips', this.node.parent);
		let logic = huTipNode.getComponent('MJWinTips');
		let cards = MJModel.getHandCardsByChairID(this.getChairID());
		cards.splice(cards.indexOf(card), 1);
		let canWinCards = MJLogic.getCanWinCards(cards, MJModel.getCanHuQidui());
		let cardsMsg = [];
		for (let card of canWinCards) {
			cardsMsg.push({
				card: card,
				count: MJModel.getRestCardCount(card),
			});
		}
		if (cardsMsg.length > 0) {
			logic.showWinCards(cardsMsg);
		}
	},

	unshowCanWinCards: function () {
		let huTipNode = cc.find('HuTips', this.node.parent);
		let logic = huTipNode.getComponent('MJWinTips');
		logic.unShow();
	},

	onDestroy: function () {
		Global.MessageCallback.removeListener('RoomMessagePush', this);
		Global.MessageCallback.removeListener('GameMessagePush', this);
		Global.MessageCallback.removeListener('ChooseCardPush', this);
	},
});
